package report

import (
	"../common"
	"../web"
	"encoding/csv"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

type QueryPoObj struct {
	common.BaseHandler
}

type PoQueryPageObj struct {
	common.BaseHandler
}

type DownloadPoObj struct {
	common.BaseHandler
}

func (self *QueryPoObj) Prepare() {}

func (self *QueryPoObj) ParameterCheck() bool {
	s_pono := self.Ctx.Params["q"]
	if s_pono != "" {
		self.Sqlparas = append(self.Sqlparas, s_pono)
		self.SqlQueryExecute()
		return false
	} else {
		s_pono = strings.TrimSpace(self.Ctx.Params["pono"])
	}
	if s_pono == "" {
		return false
	}

	self.Sqlparas = append(self.Sqlparas, s_pono)

	return true
}

func (self *QueryPoObj) SqlQueryExecute() {
	s_pono := self.Sqlparas[0].(string)

	po_ls := *common.FetchAllRowsPtr(
		`SELECT TOP 100 ROW_NUMBER() OVER(ORDER BY A.MODIFYDATE,A.PRODUCTID),A.PONO,A.PRODUCTID,
				 ISNULL(B.NAME,A.MODIFYBY),CONVERT(CHAR(23),A.MODIFYDATE,121)
		   FROM SFC_DELIVERY A(NOLOCK)
		   LEFT JOIN ShopFloorControl.dbo.SFC_EMPLOYEE B(NOLOCK)
		     ON A.MODIFYBY=B.ID
		  WHERE A.PONO=?`,
		self.Usr.Conn, new(common.PoInfo), self.Sqlparas...)

	curr_id := 1
	iRtnData := *common.FetchOneRowPtr(
		`SELECT COUNT(PONO) 
		   FROM SFC_DELIVERY(NOLOCK) 
		  WHERE PONO=?`,
		self.Usr.Conn, new(common.RecCount), self.Sqlparas...)
	recnum := iRtnData.(common.RecCount).Number
	total_id := recnum / 100
	if recnum%100 > 0 {
		total_id = total_id + 1
	}

	self.TmplData["pono"] = s_pono
	self.TmplData["curr_page"] = curr_id
	self.TmplData["total_page"] = total_id
	self.TmplData["po_ls"] = po_ls
}

func QueryPonoHandler(ctx *web.Context) {
	self := new(QueryPoObj)
	self.Ctx = ctx
	self.Html = "querypo.html"
	self.Rightlist = []string{"querypo"}
	self.DoQuery(self)
}

func (self *PoQueryPageObj) ParameterCheck() bool {
	s_pono := self.Ctx.Params["pono"]
	s_page := self.Ctx.Params["pageid"]
	if s_pono == "" {
		return false
	}
	pageid, err := strconv.Atoi(s_page)
	if err != nil {
		return false
	}

	idx := 100 * (pageid - 1)
	self.Sqlparas = append(self.Sqlparas, s_pono)
	self.Sqlparas = append(self.Sqlparas, idx)

	return true
}

func (self *PoQueryPageObj) SqlQueryExecute() {
	ponos := *common.FetchAllRowsPtr(
		`SELECT TOP 100 A.AUTOID, A.PONO, A.PRODUCTID, A.OPER, A.MDATE
           FROM
                (
                    SELECT ROW_NUMBER() OVER(ORDER BY A.MODIFYDATE,A.PRODUCTID) AS AUTOID,A.PONO,A.PRODUCTID,
                    		ISNULL(B.NAME,A.MODIFYBY) AS OPER,CONVERT(CHAR(23),A.MODIFYDATE,121) AS MDATE
				      FROM SFC_DELIVERY A(NOLOCK)
				      LEFT JOIN ShopFloorControl.dbo.SFC_EMPLOYEE B(NOLOCK)
				        ON A.MODIFYBY=B.ID
				     WHERE A.PONO=?
                ) A
          WHERE A.AUTOID > ?`,
		self.Usr.Conn, new(common.PoInfo), self.Sqlparas...)

	dict_js, _ := json.Marshal(map[string]interface{}{"ponos": ponos, "lang": self.Lang})
	self.Ctx.ResponseWriter.Write(dict_js)
}

func SplitPoByPageHandler(ctx *web.Context) {
	self := new(PoQueryPageObj)
	self.Ctx = ctx
	self.DoJsonQuery(self)
}

func (self *DownloadPoObj) ParameterCheck() bool {
	s_pono := self.Ctx.Params["pono"]

	self.Sqlparas = append(self.Sqlparas, s_pono)

	return true
}

func (self *DownloadPoObj) SqlQueryExecute() {
	s_pono := self.Sqlparas[0].(string)
	po_total := *common.FetchAllRowsPtr(
		`SELECT ROW_NUMBER() OVER(ORDER BY A.MODIFYDATE,A.PRODUCTID) AS AUTOID,A.PONO,A.PRODUCTID,
        		ISNULL(B.NAME,A.MODIFYBY) AS OPER,CONVERT(CHAR(23),A.MODIFYDATE,121) AS MDATE
	       FROM SFC_DELIVERY A(NOLOCK)
	       LEFT JOIN ShopFloorControl.dbo.SFC_EMPLOYEE B(NOLOCK)
	         ON A.MODIFYBY=B.ID
	      WHERE A.PONO=?`,
		self.Usr.Conn, new(common.PoInfo), s_pono)

	// create download file
	filename := fmt.Sprintf("PO_%s.csv", s_pono)
	f, err := os.Create(filepath.Join("download", "files", filename))
	if err != nil {
		common.Application.SendMail(fmt.Sprintf("Create download file: %s failed. Error: %v\n", filename, err))
		return
	}
	defer f.Close()

	f.WriteString("\xEF\xBB\xBF") // write UTF-8 BOM

	w := csv.NewWriter(f)
	w.Write([]string{"Index", "Purchase Order", "Product No.", "Delivery Date"})
	for _, val := range po_total {
		index := strings.TrimSpace(val.(common.PoInfo).Index)
		cpono := strings.TrimSpace(val.(common.PoInfo).PoId)
		cprod := strings.TrimSpace(val.(common.PoInfo).ProdId)
		cdate := strings.TrimSpace(val.(common.PoInfo).Date)
		w.Write([]string{"\t" + index, "\t" + cpono, cprod, "\t" + cdate})
	}
	w.Flush()

	dict_js, _ := json.Marshal(map[string]interface{}{"filename": filename})
	self.Ctx.ResponseWriter.Write(dict_js)
}

func DownloadPoHandler(ctx *web.Context) {
	self := new(DownloadPoObj)
	self.Ctx = ctx
	self.DoJsonQuery(self)
}
